package com.wan.fragment


import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.content.LocalBroadcastManager
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

import com.wan.R
import com.wan.adapter.CommonlyAdapter
import com.wan.adapter.ShowRvAdapter
import com.wan.base.BaseBean
import com.wan.entity.CommonlyEntity
import com.wan.receiver.ResultRefreshDataReceiver
import com.wan.receiver.SearchChangeTextReceiver
import com.wan.uitls.*
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagFlowLayout
import kotlinx.android.synthetic.main.fragment_search_show.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.*

/**
 *search show
 *
 */
class SearchShowFragment : Fragment(), ItemClickListener, ItemRightViewListener, TagFlowLayout.OnTagClickListener, ResultRefreshDataListener {



    private val mThreadName = this.javaClass.name

    private val hotKeyList: ArrayList<CommonlyEntity> = ArrayList()

    private val historyList: ArrayList<String> = ArrayList()

    private var historyAdapter: ShowRvAdapter? = null
    private var hotAdapter: CommonlyAdapter? = null

    private lateinit var receiver: ResultRefreshDataReceiver


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_search_show, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()
        initData()
    }


    private fun initView() {
        hotAdapter = CommonlyAdapter(context!!, hotKeyList)
        show_hot_key_tfl.adapter = hotAdapter
        show_hot_key_tfl.setOnTagClickListener(this)
        show_history_rv.layoutManager = LinearLayoutManager(context)
        historyAdapter = ShowRvAdapter(context!!, historyList, R.layout.fragment_show_rv_item_layout)
        historyAdapter!!.setDeleteListener(this)
        historyAdapter!!.setItemClickListener(this)
        show_history_rv.adapter = historyAdapter
    }

    private fun initData() {

        receiver = ResultRefreshDataReceiver(this)
        var filter = IntentFilter()
        filter.addAction(CommonUtils.Action_Search_Change_Text)
        LocalBroadcastManager.getInstance(context!!).registerReceiver(receiver, filter)


        var apiManager = ApiManager(this)
        apiManager.getHotKeys().enqueue(object : Callback<BaseBean<ArrayList<CommonlyEntity>>> {
            override fun onFailure(call: Call<BaseBean<ArrayList<CommonlyEntity>>>, t: Throwable) {
                Log.d(mThreadName, "onFailure : 热词==>${call.execute().body()}")
            }

            override fun onResponse(call: Call<BaseBean<ArrayList<CommonlyEntity>>>, response: Response<BaseBean<ArrayList<CommonlyEntity>>>) {
                Log.d(mThreadName, "onResponse : 热词==>${response.body()}")
                var data = response.body()!!.data
                hotKeyList.addAll(data)
                hotAdapter!!.notifyDataChanged()
            }
        })
        var recordList = CommonUtils.getHistory(context!!)
        if (recordList.isNotEmpty()) {
            historyList.addAll(recordList)
            historyAdapter!!.notifyDataSetChanged()
        }

    }

    /**
     * 点击 热词
     */

    override fun onTagClick(view: View?, position: Int, parent: FlowLayout?): Boolean {
        Log.e(mThreadName, "onTagClick : $position")
        var entity = hotKeyList[position]
        historyList.add(0, entity.name)
        historyAdapter!!.notifyItemInserted(0)
        Log.d(mThreadName, "onFlowItemClickListener : 点击热词回调${entity.name}");
        sendBroadcastToSearch(entity.name)
        return true
    }


    /**
     * 点击 历史记录的删除
     */
    override fun onRightViewClickListener(position: Int) {
        historyList.removeAt(position)
        historyAdapter!!.notifyItemRemoved(position)

    }

    /**
     * 点击历史记录
     */
    override fun onItemClickListener(position: Int) {
        Collections.swap(historyList, 0, position)
        historyAdapter!!.notifyDataSetChanged()
        sendBroadcastToSearch(historyList[position])
    }

    /**
     * 像查找界面发送广播
     */
    private fun sendBroadcastToSearch(text: String) {
        var intent = Intent(CommonUtils.Action_Search_Change_Text)
        intent.putExtra(CommonUtils.Search_Change_Text, text)
        LocalBroadcastManager.getInstance(context!!).sendBroadcast(intent)
    }

    override fun onResultRefreshDataListener(intent: Intent) {
        var searchText = intent.getStringExtra(CommonUtils.Search_Text)
        historyList.add(0, searchText)
        historyAdapter!!.notifyItemInserted(0)
    }



    override fun onDestroy() {
        super.onDestroy()
        CommonUtils.saveHistory(context!!, historyList)
        RetrofitHelper.get().cancelCall(this)
        LocalBroadcastManager.getInstance(context!!).unregisterReceiver(receiver)
    }


}
